package com.steven.ourcontest.main.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import com.steven.ourcontest.R
import com.steven.ourcontest.chat.widget.OnSelectListener
import kotlinx.android.synthetic.main.view_main_tab.view.*

class MainTabBar(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs) {

    companion object {
        const val TAB_MAIN = 0
        const val TAB_CONTEST = 1
        const val TAB_FORUM = 2
        const val TAB_ME = 3
    }

    var currentTab = -1
    var selectListener: OnSelectListener? = null

    init {
        LayoutInflater.from(context).inflate(R.layout.view_main_tab, this, true)

        iv_main?.setImageResource(R.drawable.ic_tab_home_unselected)
        iv_contest?.setImageResource(R.drawable.ic_tab_contest_unselected)
        iv_forum?.setImageResource(R.drawable.ic_tab_news_unselected)
        iv_me?.setImageResource(R.drawable.ic_tab_mine_unselected)
        setCurrentItem(TAB_MAIN)

        ll_main?.setOnClickListener {
            setCurrentItem(TAB_MAIN)
        }
        ll_contest?.setOnClickListener {
            setCurrentItem(TAB_CONTEST)
        }
        ll_forum?.setOnClickListener {
            setCurrentItem(TAB_FORUM)
        }
        ll_me?.setOnClickListener {
            setCurrentItem(TAB_ME)
        }
    }

    fun setCurrentItem(index: Int) {
        if (currentTab == index) {
            return
        }
        if (selectListener?.onSelected(currentTab, index) == false) {
            return
        }
        when (currentTab) {
            TAB_MAIN -> {
                iv_main?.setImageResource(R.drawable.ic_tab_home_unselected)
            }
            TAB_CONTEST -> {
                iv_contest?.setImageResource(R.drawable.ic_tab_contest_unselected)
            }
            TAB_FORUM -> {
                iv_forum?.setImageResource(R.drawable.ic_tab_news_unselected)
            }
            TAB_ME -> {
                iv_me?.setImageResource(R.drawable.ic_tab_mine_unselected)
            }
        }
        when (index) {
            TAB_MAIN -> {
                iv_main?.setImageResource(R.drawable.ic_tab_home_selected)
            }
            TAB_CONTEST -> {
                iv_contest?.setImageResource(R.drawable.ic_tab_contest_selected)
            }
            TAB_FORUM -> {
                iv_forum?.setImageResource(R.drawable.ic_tab_news_selected)
            }
            TAB_ME -> {
                iv_me?.setImageResource(R.drawable.ic_tab_mine_selected)
            }
        }
        currentTab = index
    }
}

interface OnSelectListener {
    fun onSelected(current: Int, index: Int): Boolean
}